package com.zb.zeus.common.datasource.handler;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import com.zb.zeus.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

/**
 * @author fujianjian
 * @date 2021/8/26 16:11
 **/
@Slf4j
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Set.class)
public class SetTextFieldTypeHandler extends BaseTypeHandler<Set<String>> {
    private final static char CH = 95;


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Set<String> stringSet, JdbcType jdbcType) throws SQLException {
        String fatalVal = null;
        if (CollectionUtils.isNotEmpty(stringSet)) {
            fatalVal = Joiner.on(CH).join(stringSet);
        }
        preparedStatement.setString(i, fatalVal);

    }


    @Override
    public Set<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String textVal = resultSet.getString(s);
        Set<String> fatalVal = null;
        if (StringUtils.isNotEmpty(textVal)) {
            Iterable<String> iterable = Splitter.on(CH).split(textVal);
            fatalVal = Sets.newHashSet(iterable);
        }
        return fatalVal;
    }

    @Override
    public Set<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String textVal = resultSet.getString(i);
        Set<String> fatalVal = null;
        if (StringUtils.isNotEmpty(textVal)) {
            Iterable<String> iterable = Splitter.on(CH).split(textVal);
            fatalVal = Sets.newHashSet(iterable);
        }
        return fatalVal;
    }

    @Override
    public Set<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String textVal = callableStatement.getString(i);
        Set<String> fatalVal = null;
        if (StringUtils.isNotEmpty(textVal)) {
            Iterable<String> iterable = Splitter.on(CH).split(textVal);
            fatalVal = Sets.newHashSet(iterable);
        }
        return fatalVal;
    }
}
